const path = require('path')
const config = require('./config')
const jsonServer = require('json-server')
let rules = require('./router')
const dbfile = require(config.DB_FILE)
const ip = config.SERVER
const port = config.PORT
const server = jsonServer.create()
// replace router key
const randomKey = () => {
	let letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwzxy'.split('')
	for (let index = 0; index < letters.length; index++) {
		let random = parseInt(Math.random() * letters.length)
		let temp = letters[index]
		letters[index] = letters[random]
		letters[random] = temp
	}
	letters = letters.join('')
	return `_${letters.substring(0, 30)}`
}
let randomKeyMap = {}
let DB = dbfile.default
Object.keys(DB).forEach(element => {
	let rkey = randomKey()
	randomKeyMap[element] = '/'+ rkey
	DB[rkey] = DB[element]
	delete DB[element]
});
rules = Object.assign(rules, randomKeyMap)
const router = jsonServer.router(DB)
const middlewares = jsonServer.defaults()
server.use(jsonServer.bodyParser)
server.use(middlewares)
server.use((req, res, next) => {
 	res.header('X-Hello', 'World')
 	next()
})
router.render = (req, res) => {
	res.jsonp({
		code: 0,
		body: res.locals.data
	})
}
server.use(jsonServer.rewriter(rules))
server.use(router)
server.listen({
	host: ip,
	port: port,
}, function() {
	console.log(config.COLOR.cyan, `\t*************************************************`)
	console.log(config.COLOR.green, `\t\t`)
	console.log(config.COLOR.green, `\tJSON Server is running in http://${ip}:${port}`)
	console.log(config.COLOR.green, `\t\t`)
	console.log(config.COLOR.cyan, `\t*************************************************`)
	console.log(config.COLOR.green, `\t\t`)
	console.log(config.COLOR.cyan, `\t*************************************************`)
	console.log(config.COLOR.green, `\t\t`)
	console.log(config.COLOR.green, `\tJSON Server custom router`)
	console.log(config.COLOR.green, `\t\t`)
	Object.keys(randomKeyMap).forEach(element => {
		console.log(config.COLOR.green, `\t${element}\t\t\t${randomKeyMap[element]}`)
	});
	console.log(config.COLOR.green, `\t\t`)
	console.log(config.COLOR.cyan, `\t*************************************************`)
})
